<?php
namespace Admin\Controller;
use Common\Controller\AdminBaseController;

use Think\Controller;
use Common\Controller\CommonActions\OrgnizerActionController as OrgC;

/**
 * 后台首页控制器
 */
class OrgnizerController extends AdminBaseController{

    /**
     * 设定管理模式的oid
     * @param $oid
     */

    public function __construct()
    {
        parent::__construct();

        $this->oid = session("adminoid");

    }


    public function testexcel()
{
	Vendor('Excel.reader');
	$xls = new \Spreadsheet_Excel_Reader();
	var_dump($xls);
}

    public function setOid($oid)
    {
        session("adminoid", $oid);
        $this->ajaxReturn(1);
    }

    public function deleteOrgnizer($oid)
    {
        $uidlist = M("orgnizeruserclass")->where(['oid' => $oid])->select();
        $status = D("Users")->deleteUsers($uidlist);
        if ($status['code'] == 1){
            M("orgnizers")->where(['oid' => $oid])->delete();
            M("orgnizer_grouptest")->where(['oid' => $oid])->delete();
            $this->ajaxReturn(['code' => 1, 'msg'=>"删除成功"]);
        }

    }

    public function addOrgnizer()
    {
        $userdata['username'] = I("username");
        $userdata['password'] = I("userpasswd");
        $userdata['email'] = I("email");
        $userdata['age'] = I("age");
        $userdata['sex'] = I("sex");
        if($userdata['sex'] == '男')
            $userdata['sex'] = 'male';
        else
            $userdata['sex'] = 'female';


        $orgnizerdata['orgnizer_name'] = I("orgnizername");
        $orgnizerdata['orgnizer_info'] = I("orgnizerinfo");

        $user = D("Users");
        if (!$data = $user->create($userdata)) {
            // 防止输出中文乱码
            header("Content-type: text/html; charset=utf-8");
            $rs['code'] = -1;
            $rs['msg'] = $user->getError();

        }

        else{
            $uid = $user->add($data);
            $orgnizerdata['uid'] = $uid;
            if (M("orgnizers")->add($orgnizerdata)){
                $rs['code'] = 1;
                $rs['msg'] ="添加成功！";
            }
            else{
                $rs['code'] = -1;
                $rs['msg'] ="添加失败！";
            }

        }

        $this->ajaxReturn($rs);

    }


    public function show_TempQuizList()
    {
        if (IS_AJAX){
            $tempquiz_list = M('tempquiz_list');
            $data = $tempquiz_list->where(['oid' => $this->oid])->select();
            $this->ajaxReturn($data);
        }
    }


    public function generate_quiz()
    {
        if (IS_AJAX){
            $quiz_num = I('quiz_num');
            $quiz_type = I('quiz_type');
            $tempquiz_list = M('tempquiz_list');

            if(!$this->oid){
                $rs['code'] = -1;
                $rs['msg'] = '您不是组织评测者！';
                $this->ajaxReturn($rs);
                return;
            }

            for($i = 0; $i < $quiz_num; $i++){
                $data['quiz_key'] = String::randString(8,2);
                $data['oid'] = $this->oid;
                $data['quiz_type'] =$quiz_type;

                $tempquiz_list->add($data);
            }

            $rs['code'] = 1;
            $rs['msg'] = '测试链接生成成功！';
            $this->ajaxReturn($rs);

        }
    }

    /**
     * 加载组织者组织结构信息
     */

    public function getClassInfoTree()
    {
        $rs = OrgC::getClassInfoTree($this->oid);
        if ($rs){
            echo $rs;
        }
        else{
            $this->ajaxReturn(['code'=>-1]);
        }

    }

    /**
     * 取得当前组织名
     */

    public function getOrgName()
    {
        $this->ajaxReturn(OrgC::getOrgnizerName($this->oid));
    }


    /**
     * 批量添加用户
     */

    public function addJsonUserData()
    {
        $this->ajaxReturn(OrgC::addJsonUserData(I_withoutReplace("jsondata"), I_withoutReplace("classinfo"), $this->oid));
    }

    /**
     * 取得用户列表
     */
    public function getUserList()
    {
        $jsonpara = I_withoutReplace("searchkey");
        $this->ajaxReturn(OrgC::getUserList($this->oid, $jsonpara));
    }

    /**
     * 更新用户信息
     */
    public function updateUserInfo()
    {
        $uid = I("uid");
        $data['username'] = I('username');
        $data['email'] = I('useremail');
        $data['password'] = I('userpassword');

        $this->ajaxReturn(OrgC::updateUserinfo($uid, $data));
    }

    /**
     * 批量删除用户（包含报告）
     */

    public function deleteUsers()
    {
        $this->ajaxReturn(OrgC::deleteUsers(I_withoutReplace("userlist")));
    }


    /**
     * 更新对应组织信息
     */
    public function updateClassInfo()
    {
        OrgC::updateClassInfo($this->oid, I_withoutReplace("class_info"));
        $rs['msg'] = '更新组织信息操作成功';
        $this->ajaxReturn($rs);
    }

    /**
     * 批量删除子级下面的用户
     */

    public function deleteSubClass()
    {
        $classJson = I_withoutReplace("classJson");

        $users = M("orgnizeruserclass")->where(['oid' => $this->oid, 'class' => $classJson])->select();
        //删除用户
        D("Common/Users")->deleteUsers($users);
        //返回给前台并且删除标签更新列表

        $this->ajaxReturn(["code" => 1, "msg" => "操作成功！"]);
    }


    /**
     * 返回班级列表json
     */

    public function getClassArray()
    {

        $arr = OrgC::getClassArray($this->oid);
        //var_dump($arr);

        //id意思每个一级或者二级元素的名称
        $result = [];
        $class_in_quizlist = M("orgnizeruserclass")->join("orgnizer_userquizlist on orgnizer_userquizlist.uid = orgnizeruserclass.uid")
            ->where(['orgnizeruserclass.oid' => $this->oid])->select();

        foreach($arr as $class){
            $id = $class['id'];

            foreach($class['children'] as $children){
                $str = $id.", ".$children['id'];
                $rs['class_1'] = $id;
                $rs['class_2'] = $children['id'];

                $count = M('orgnizeruserclass')->where(['oid' => $this->oid, 'class' => json_encode($rs,JSON_UNESCAPED_UNICODE)])->count();

                $result[] = [
                    'class_str' => $str,
                    'class_json' => json_encode($rs,JSON_UNESCAPED_UNICODE),
                    'count' => $count
                ];


            }
        }

        foreach($result as $key=>$value){
            foreach($class_in_quizlist as $in_quizlist_jsonstr){
                if ($value['class_json'] == $in_quizlist_jsonstr['class']){
                    $result[$key]['count'] = "-2";//已在列表里的元素
                    //unset($result[$key]);
                }
            }
        }

        $this->ajaxReturn($result);

    }



    public function newQuiz()
    {


        if (IS_AJAX){


            $grouptest = M("orgnizer_grouptest");
            $isvisible = I("isvisible");
            $classlist_str = I_withoutReplace("classlist_str");
            $json_quiz_list = I_withoutReplace("json_quiz_list");
            $quizinfo = I("quizinfo");
            $quiztitle = I("quiztitle");


            $data['oid'] = $this->oid;
            $data['quiz_list'] = $json_quiz_list;

            if(!$quiztitle){
                $this->ajaxReturn(['code' => -1, 'msg'=>"问卷标题必须！"]);
                return;
            }

            if ($grouptest->where(['title' => $quiztitle, 'oid' => $this->oid])->select()){
                $this->ajaxReturn(['code' => -1, 'msg'=>"这个问卷测试的标题已经被占用了"]);
                return;
            }
            $data['title'] = $quiztitle;
            $data['timestamp'] = time();
            $data['warnvalue'] = '[]';
            $data['info'] = $quizinfo;
            $data['isvisible'] = $isvisible;




            $group_id = $grouptest->add($data);

            preg_match_all('/{.*?}/',$classlist_str ,$class_list);

            $userdao = D('Common/Orgnizeruserclass');

            foreach($class_list[0] as $class_json){
                $userlist = $userdao->getUserList($this->oid, $class_json);

                foreach($userlist as $user){
                    $rs['uid'] = $user['uid'];
                    $rs['testgroup_id'] = $group_id;
                    $rs['oid'] = $this->oid;
                    M('Orgnizer_userquizlist')->add($rs);
                }

            }

            $this->ajaxReturn(['code' => 1, 'msg'=>"添加测试成功！可以在后台查看被测者的完成进度等信息"]);

        }

        else{
            $this->display();
        }

    }



    public function showQuizStatus()
    {

        $quiztitle = I("quiztitle");


        $list = D('Orgnizer_grouptest')->getUserQuizList($quiztitle);

        foreach ($list as &$item){
            $item['timestamp'] = date("Y-m-d H:i",$item['timestamp']);

        }


        $this->ajaxReturn($list);


    }


    public function showQuizStatusDetail()
    {
        $quiz_list = I_withoutReplace("quiz_list_json");
        $uid = I("uid");

        $quiz_list = json_decode($quiz_list);

        $rs = D("User_answer")->QuizDetail($quiz_list, $uid);


        $this->ajaxReturn($rs);


    }


    public function getQuizTitleList()
    {
//        if (IS_AJAX){
//            $quiztitles = M('orgnizer_userquizlist')->field('quiztitle')->group("quiztitle")->where(['oid' => $this->oid])->select();
//            $this->ajaxReturn($quiztitles);
//        }

        $rs = M('Orgnizer_grouptest')->where(['oid' => $this->oid])->select();
        if (!$rs)
            $this->ajaxReturn(['code' => -1]);
        else{
            $this->ajaxReturn($rs);
        }

        $this->ajaxReturn(M('Orgnizer_grouptest')->where(['oid' => $this->oid])->select());

        // var_dump(D('Orgnizer_grouptest')->getUserQuizList(8));

    }




    //下面这些显示报告的方法放到具体问卷的控制器中去


    public function show_userReport($uid, $quiz_id)
    {
        if($quiz_id == 7){
            $ctl = A("Quiz/Wippf");
            $ctl->show_wippf($uid);
        }
        else if($quiz_id == 6){
            $ctl = A("Quiz/Pf16");
            $ctl->show_16pf($uid);
        }
    }

    public function show_groupReport($quiz_name, $quiz_grouptitle)
    {
        if ($quiz_name =="16pf_test"){
            $ctl = A("Quiz/Pf16");
            $ctl->show_16pf_groupreport($this->oid, $quiz_grouptitle);
        }
        else if ($quiz_name == "wippf_demo"){
            $ctl = A("Quiz/Wippf");
            $ctl->show_wippf_groupreport($this->oid, $quiz_grouptitle);
        }
    }

    /**
     * 下载单个用户报告
     * @param $uid
     * @param $quiz_id
     */

    public function downloadUserReportPdf($uid, $quiz_id)
    {
        A('Common/OutputFile')->outUserReport($uid, $quiz_id);
    }





    public function show_16pf($uid)
    {
        $ctl = A("Type16pf");
        $result = $ctl->show_16pf($uid );
        $this->assign("result", $result);
        $this->display("Type16pf:show_16pf");
    }

    public function show_16pf_groupreport($quiztitle)
    {
        $ctl = A("Type16pf");
        $rs = $ctl->show_16pf_groupreport($this->oid, $quiztitle);
        $this->assign("element_name", $rs['element_name']);
        $this->assign('result_table', $rs['result_table']);
        $this->display("Type16pf:show_16pf_groupreport");
    }

    public function setWarnValue($quiz_grouptitle)
    {
        if(IS_AJAX){
            $ctl = A("Quiz/Quiz");
            $ctl->setWarnValue($this->oid, $quiz_grouptitle);
        }
    }

    public function getWarnValue($quiz_grouptitle)
    {
        if(IS_AJAX){
            $ctl = A("Quiz/Quiz");
            $ctl->getWarnValue($this->oid, $quiz_grouptitle);
        }

    }

    public function deleteGroupTest($grouptest_id)
    {

        //删除对应答案
        $uid_list = M("orgnizer_userquizlist")->where(['testgroup_id' => $grouptest_id])->field(['uid'])->select();
        foreach($uid_list as $uid){
            M("calc_result")->where(["user_id" => $uid['uid']])->delete();
            M("user_answer")->where(["user_id" => $uid['uid']])->delete();
        }

        //删除对应组别下面的测试列表

        M("orgnizer_userquizlist")->where(['testgroup_id' => $grouptest_id])->delete();
        M("orgnizer_grouptest")->where(['testgroup_id' => $grouptest_id])->delete();

        $this->ajaxReturn(["msg" => "删除成功！", "code" => 1]);

    }

//    public function getWarnKey(){
//        $ctl = A("Type16pf");
//        $ctl->getWarnKey();
//    }

    public function xlsReaderTest()
    {
        $classinfo = I('classinfo');
        $classinfo = str_replace("&quot;", "\"",$classinfo);

        include_once("/Excel/reader.php");

        $xls = new Spreadsheet_Excel_Reader();
        $xls->setOutputEncoding('utf-8');  //设置编码
        $xls->read("D:\\wamp\\www\\xinqiji\\Uploads\\test_userimport.xls");  //解析文件

        $data = [];
        $k = 0;
        for ($i=2; $i<=$xls->sheets[0]['numRows']; $i++) {
            $data[$k]['username'] = $xls->sheets[0]['cells'][$i][1];
            $data[$k]['email'] = $xls->sheets[0]['cells'][$i][2];
            $data[$k]['password'] = md5($xls->sheets[0]['cells'][$i][3]);
            //$data_values .= "('$name','$sex','$age'),";
            $k++;
        }

        $user = M("users");
        $user_class = M('orgnizeruserclass');
        $rs = [];
        foreach($data as $j){
            $j['oid'] = $this->oid;

            if($user->create($j)){
                $uid = $user->add();
                if ($user_class->add(['oid' => $this->oid, 'class' => $classinfo, 'uid' => $uid])){
                    $rs['msg'] = '操作成功！';
                }
                else{
                    $rs['msg'] = $user_class->getError();
                }
            }
            else{
                $rs['msg'] = $user->getError();
            }
        }

        $this->ajaxReturn($rs);

//        header("Content-type: text/html; charset=utf-8");
//        var_dump($data);
    }

    public function xlsImportUserAll()
    {

        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('xls');// 设置附件上传类型
        $upload->rootPath  =     './Uploads/userdata_xls/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息

            $status['msg'] = $upload->getError();
            $status['code'] = -2;
            $this->ajaxReturn($status);
            return;

        }

        else{
            $filepath = $_SERVER['DOCUMENT_ROOT'].'/Uploads/userdata_xls/'.$info['file']['savepath'].$info['file']['savename'];
        }

	Vendor('Excel.reader');
        //include_once("/Excel/reader.php");
        $xls = new \Spreadsheet_Excel_Reader();
        $xls->setOutputEncoding('utf-8');  //设置编码
        $xls->read($filepath);  //解析文件

        $classarray = OrgC::getClassArray($this->oid);


        foreach($classarray as $class){
            $id = $class['id'];

            foreach($class['children'] as $children){
                $rs['class_1'] = $id;
                $rs['class_2'] = $children['id'];
                $origin_class_json_strs[] = json_encode($rs,JSON_UNESCAPED_UNICODE);
            }
        }

        // var_dump($xls->boundsheets);

        $sheet_names = [];

        foreach($xls->boundsheets as $row){
            $sheet_names[] = $row['name'];
        }

        //$xls->boundsheets; 工作簿名称数组

        // var_dump($origin_class_json_strs);

        $names_rs = [];
        foreach($sheet_names as $key=>$names){
            preg_match_all("/(.*),(.*)/", $names, $names_rs[$key]);
        }


        //  var_dump($names_rs);


        $name_id = $names_rs[0][1][0];
        $new_class_info_arr = [];
        $key = 0;
        foreach($names_rs as $n){
            $rs['class_1'] = $n[1][0];
            $rs['class_2'] = $n[2][0];
            $new_class_json_strs[] = json_encode($rs,JSON_UNESCAPED_UNICODE);

            if($name_id != $n[1][0]){
                $name_id = $n[1][0];
                $key++;
            }
            $new_class_info_arr[$key]['id'] = $name_id;
            $new_class_info_arr[$key]['children'][]['id'] = $n[2][0];
        }

        //var_dump($new_class_json_strs);//新的json信息班级名称列表


        //检查重复

        foreach($new_class_json_strs as $new_str){
            foreach($origin_class_json_strs as $old_str){
                if($new_str == $old_str){
                    $status['msg'] = $new_str."重复了";
                    $status['code'] = -1;
                    $this->ajaxReturn($status);

                    return;
                }
            }
        }

        // 遍历每一个sheet入库用户信息
        //增加判空 报错退出


        $sheet_num = 0;
        foreach($names_rs as $n){
            $rs['class_1'] = $n[1][0];
            $rs['class_2'] = $n[2][0];
            $class_json_str = json_encode($rs,JSON_UNESCAPED_UNICODE);

            $data = [];
            $k = 0;
            for ($i=2; $i<=$xls->sheets[$sheet_num]['numRows']; $i++) {
                $data[$k]['username'] = $xls->sheets[$sheet_num]['cells'][$i][1];
                $data[$k]['email'] = $xls->sheets[$sheet_num]['cells'][$i][2];
                $data[$k]['password'] = $xls->sheets[$sheet_num]['cells'][$i][3];
                $data[$k]['sex'] = $xls->sheets[$sheet_num]['cells'][$i][4];
                $data[$k]['age'] = $xls->sheets[$sheet_num]['cells'][$i][5];
                //$data_values .= "('$name','$sex','$age'),";
                $k++;
            }

            foreach($data as $row){
                foreach($row as $key=>$value){
                    if(!$value){
                        $status_return['msg'] = $key."不能为空！";
                        $status_return['code'] = -1;
                        $this->ajaxReturn($status_return);
                        exit;
                    }
                }
            }


            //var_dump($data);
            $status = D('Common/Users')->addOrgnizerUsers($data, $class_json_str, $this->oid);

            if ($status['code'] == -1){

                $status_return['msg'] = $status['msg'];
                $status_return['code'] = -1;
                $this->ajaxReturn($status_return);
                exit;
            }

            $sheet_num++;

        }


        //添加新的组织结构进入数据库

        $class_json = M('orgnizers')->where(['oid'=>$this->oid])->field('class_info')->select();
        $class_json = $class_json[0]['class_info'];

        $origin_class_list = json_decode($class_json, true);


        //var_dump($new_class_info_arr);

        if(!$origin_class_list)
            $origin_class_list = [];

        foreach($new_class_info_arr as $new_class_info){
            array_push( $origin_class_list, $new_class_info);
        }
        //var_dump($origin_class_list);//新增加的树形列表

        //更新组织树形里列表

        OrgC::updateClassInfo($this->oid, json_encode($origin_class_list,JSON_UNESCAPED_UNICODE ));

        $status_return['msg'] = "导入成功！";
        $status_return['code'] = 1;
        $this->ajaxReturn($status_return);

    }


}
